//
//  PYMySinglePyqDetailViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/8.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView


class PYMySinglePyqDetailViewController: SYBaseTableViewController, UITableViewDelegate {
    
    
    let presenter = PYPresenter()
    
    var id: String!
    var datas:[PYMyDetailModel] = []
    
    init(id: String) {
        super.init(nibName: nil, bundle: nil)
        self.id = id
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false
        
        setTableView()
        setNoDataView()
        
        requestDetail(id: self.id)
        
        self.title = "详情"
    }
    
    func requestDetail(id:String) {
        requestVM.baseRequest(disposeBag: dispose, type: .myDetail(id: id), modelClass: SGBaseModel<PYMyDetailModel>.self) {[weak self] (res) in
            if let `self` = self {
                self.datas.append(res.data ?? PYMyDetailModel())
                self.loadDataSuccessed()
            }
            
        } Error: {
            
        }
    }
    
    func requestDelete(id:Int, complete:@escaping (Bool)->()) {
        requestVM.baseRequest(disposeBag: dispose, type: .deleteMy(id: id), modelClass: SGBaseModel<PYMyDetailModel>.self) {[weak self] (res) in
            if let `self` = self {
                
                complete(true)
            }
            
        } Error: {
            complete(false)
        }
    }
    
    func loadDataSuccessed() {
        
        DispatchQueue.main.async {
            self.setDataSource()
        }
    }
    
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT - BOTTOM_SAFE_HEIGHT), style:.plain)
        //        self.tableView.rowHeight = 100
        //        self.tableView.rowHeight = UITableView.automaticDimension
        self.tableView.separatorStyle = .none
        self.tableView.delegate = self
        //创建一个重用的单元格
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)
        
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT - 200.0.autoWidth()))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        
        let sections = Observable.just([
            PYMyDetailSection(header: "", items: self.datas)
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<PYMyDetailSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                let cell: PYMyDetailCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? PYMyDetailCell ?? PYMyDetailCell(style: .default, reuseIdentifier: "Cell")
                
                cell.cellIndexPath = ip
                cell.delegate = self.presenter
                cell.selectionStyle = .none
                cell.currentVC = self
                // 过滤
                //                item.resourceList?.filter({ return $0.videoImgUrl})
                //                let pics: Array<String> = (model.data?.map{ IMGIP + $0.picPath! + $0.picName! })!
                var videoImgUrls: [String] = []
                var isVideo = false
                item.resourceList?.forEach({ (value) in
                    if let u = value.videoImgUrl {
                        isVideo = true
                        videoImgUrls.append(String(format: "%@%@", IMGIP, u))
                    } else if let l = value.fileFullPath {
                        videoImgUrls.append(String(format: "%@%@", IMGIP, l))
                    }
                })
                print("第一个cell\(ip.row)，共\(videoImgUrls.count)张image")
                cell.configureMyDetailCell(urls: videoImgUrls, model: item, isVideo: isVideo)
                
                return cell
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    @objc func rightAction() {
        
    }
    
}



//自定义Section
struct PYMyDetailSection {
    var header: String
    var items: [Item]
}

extension PYMyDetailSection : AnimatableSectionModelType {
    typealias Item = PYMyDetailModel
    
    var identity: String {
        return header
    }
    
    init(original: PYMyDetailSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension PYMyDetailModel: IdentifiableType {
    var identity: String {
        return id!
    }
    
    typealias Identity = String
}
